package com.example.springbootmybatis.controller;

import com.example.springbootmybatis.entity.RestResult;
import com.example.springbootmybatis.entity.User;
import com.example.springbootmybatis.service.IndexService;
import com.example.springbootmybatis.utility.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @title: IndexController
 * @Author Tan
 * @Date: 2021/6/24 14:45
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/user")
public class IndexController {
    @Resource
    private IndexService indexService;

    @RequestMapping(value = "/index")
    public String Index() {
        // 此时访问templetes文件夹下的index.html文件（游戏登录界面）
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult<Map<String, Object>> Login(@RequestParam(value = "name") String name,
                                                 @RequestParam(value = "password") String password,
                                                 HttpServletRequest servletRequest) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 判断是否有用户名和密码
        if (!StringUtils.hasText(name) || !StringUtils.hasText(password)) {
            return ResultUtil.genErrorResult("001");
        }

        if (indexService.loginCheck(name, password)) {
            // 拿到权限后，存储用户信息到session中
            HttpSession httpSession = servletRequest.getSession();
            User user = new User(name, password);
            httpSession.setAttribute("user", user);
            // 此时访问templetes文件夹下的mainview.html文件（游戏登录界面）
            map.put("isCheck", true);
            return ResultUtil.genSuccessResult(map);
        } else {
            return ResultUtil.genErrorResult("001");
        }
    }

    @PostMapping(value = "/dashboard")
    // 上方注释等同于@RequestMapping(value = "/dashboard", method = RequestMethod.POST)
    public String ShowDashBoard() {
        return "dashboard";
    }

    @GetMapping(value = "/indexgame")
    public String ShowIndexgame() {
        return "indexgame";
    }
}
